﻿using System;
using System.Collections.Generic;
using System.Text;

using Asp = System.Web;
using Daco.Web.Store;

namespace Daco.Web.UI.WebControls
{
    public class CategoryTree<VALUE, TYPE> : Asp.UI.WebControls.WebControl, Asp.UI.IPostBackDataHandler, Asp.UI.IPostBackEventHandler where TYPE: class, new()
    {
        private IEnumerable<ICategory<VALUE, TYPE>> _dataSource = null;
        public IEnumerable<ICategory<VALUE, TYPE>> DataSource
        {
            get { return _dataSource; }
            set { _dataSource = value; }
        }

        private string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                if (!string.IsNullOrEmpty(value) && (string.IsNullOrEmpty(_title) || string.Compare(value, _title, StringComparison.CurrentCultureIgnoreCase) == 0))
                    _title = value;
            }
        }

        private ICategory<VALUE, TYPE> _selectedCategory = null;
        public ICategory<VALUE, TYPE> SelectedCategory
        {
            get { return _selectedCategory; }
            set { _selectedCategory = value; }
        }

        public override string ClientID
        {
            get
            {
                return string.Format("DACO_WebControl_CategoryTree_" + this.GetHashCode());
            }
        }

        public override string UniqueID
        {
            get
            {
                return string.Format("DACO$WebControl$CategoryTree$" + this.GetHashCode());
            }
        }

        public CategoryTree() : base( Asp.UI.HtmlTextWriterTag.Div)
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            // Register postback event
            Page.RegisterRequiresPostBack(this);
            // Register event raise
            Page.RegisterRequiresRaiseEvent(this);
        }

        protected override void Render(Asp.UI.HtmlTextWriter writer)
        {
            writer.WriteLine(@"<div class=""DIVBox"">
                            <div class=""DIVBoxHeader"">
                                <div><h4>{0}</h4></div>
                            </div>
                            <div class=""DIVBoxContent"">
                                <div>", Title);
            writer.WriteLine(@"<ul class=""ULLineHeight150"">");
            foreach (ICategory<VALUE, TYPE> category in DataSource)
            {
                // Write begin LI
                writer.Write(@"<li class=""{0}""><a class=""title"" href=""{2}"" title=""{1}"" >{1}</a>", category.ChildCategories.Count > 0 ? "LISquare" : "LIArrow", category.Title, GetRewriteUrl(category));

                // Write children
                if (category.ChildCategories.Count > 0)
                    RenderNodes(writer, (IEnumerable<ICategory<VALUE, TYPE>>)category.ChildCategories);

                // Write end LI
                writer.WriteLine("</li>");
            }
            writer.WriteLine("</ul>");

            writer.WriteLine(@"</div>
                        </div>
                    </div>");
        }
        /// <summary>
        /// Render child categories
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="categories"></param>
        private void RenderNodes(Asp.UI.HtmlTextWriter writer, IEnumerable<ICategory<VALUE, TYPE>> categories)
        {
            writer.WriteLine("<ul>");
            foreach (ICategory<VALUE, TYPE> category in categories)
            {
                // Write begin LI
                writer.Write(@"<li class=""{0}""><a class=""title"" href=""{2}"" title=""{1}"" >{1}</a>", category.ChildCategories.Count > 0 ? "LISquare" : "LIArrow", category.Title, GetRewriteUrl(category));

                // Write children
                if (category.ChildCategories.Count > 0)
                    RenderNodes(writer, (IEnumerable<ICategory<VALUE, TYPE>>)category.ChildCategories);

                // Write end LI
                writer.WriteLine("</li>");
            }
            writer.WriteLine("</ul>");
        }

        private bool IsTreeSelected(ICategory<VALUE, TYPE> match)
        {
            if (SelectedCategory == null) return false;
            else
            {
                if (SelectedCategory == match)
                    return true;
                else
                {
                    ICategory<VALUE, TYPE> parent = SelectedCategory.ParentCategory;
                    while (parent != null)
                        if (parent == match) return true;
                        else parent = parent.ParentCategory;

                    return false;
                }
            }
        }

        private string GetRewriteUrl(ICategory<VALUE, TYPE> category)
        {
            return Page.ResolveUrl(string.Format("~/EStore/Catalog.aspx?cl={0}&title={1}", category.CategoryID, category.EncodedTitle));
        }

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            return false;
        }

        public void RaisePostDataChangedEvent()
        {
        }

        public void RaisePostBackEvent(string eventArgument)
        {
        }
    }
}
